package com.hk.yajin.function;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.hk.developmentlib.utills.FastjsonUtils;
import com.hk.developmentlib.utills.constants.BroadcastConstants;
import com.hk.yajin.R;
import com.hk.yajin.base.BaseActivity;
import com.hk.yajin.function.index.MenuIndexFragment;
import com.hk.yajin.function.members.activity.LoginAndRegisterActivity;
import com.hk.yajin.function.members.fragment.MenuMemberFragment;
import com.hk.yajin.function.messages.MenuMessageFragment;
import com.hk.yajin.function.news.MenuNewsFragment;
import com.hk.yajin.function.videos.MenuVideoFragment;
import com.hk.yajin.manager.UserInfoManager;
import com.hk.yajin.model.Message;
import com.hk.yajin.model.PushModel;
import com.hk.yajin.utills.MessageHelper;

import org.xutils.common.util.LogUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

public class MainActivity extends BaseActivity implements RadioGroup.OnCheckedChangeListener {

    private RadioGroup rg_tab;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initBroadcastReceiver();
        handleIntentWithPushData(getIntent());

    }

    private void handleIntentWithPushData(Intent intent) {
        if (intent != null && !TextUtils.isEmpty(intent.getStringExtra(PUSH_DATA))) {
            PushModel pushModel = FastjsonUtils.getBeanObject(intent.getStringExtra(PUSH_DATA), PushModel.class);
            if ("mail".equals(pushModel.getType())) {
                ((RadioButton) findViewById(R.id.rb_four)).setChecked(true);
            }
        }
    }

    private void initBroadcastReceiver() {
        broadcastReceiver = new RefreshMessageReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BroadcastConstants.ACTION_USER_LOGIN);
        intentFilter.addAction(BroadcastConstants.ACTION_USER_LOGINOUT);
        registerReceiver(broadcastReceiver, intentFilter);
    }

    private void initView() {
        //初始化RadioGroup
        rg_tab = (RadioGroup) findViewById(R.id.rg_tab);
        rg_tab.setOnCheckedChangeListener(this);
        rg_tab.check(R.id.rb_one);
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        Fragment fm = null;

        switch (checkedId) {
            case R.id.rb_one:
                rg_tab.setTag(FragmentFlag.FRAGMENT_ONE);
                fm = createFragment(FragmentFlag.FRAGMENT_ONE);
                break;

            case R.id.rb_two:
                rg_tab.setTag(FragmentFlag.FRAGMENT_TWO);
                fm = createFragment(FragmentFlag.FRAGMENT_TWO);
                break;

            case R.id.rb_three:
                rg_tab.setTag(FragmentFlag.FRAGMENT_THREE);
                fm = createFragment(FragmentFlag.FRAGMENT_THREE);
                break;
            case R.id.rb_four:
                rg_tab.setTag(FragmentFlag.FRAGMENT_FOUR);
                fm = createFragment(FragmentFlag.FRAGMENT_FOUR);
                break;
            case R.id.rb_five:
                rg_tab.setTag(FragmentFlag.FRAGMENT_FIVE);
                fm = createFragment(FragmentFlag.FRAGMENT_FIVE);
                break;
        }
        replaceFragment(fm);
    }

    /**
     * 记录所有的fragment，防止重复创建
     */
    private Map<FragmentFlag, Fragment> mFragmentMap = new HashMap<>();

    public enum FragmentFlag {
        FRAGMENT_ONE,            // 首页
        FRAGMENT_TWO,            // 新闻
        FRAGMENT_THREE,          //视频
        FRAGMENT_FOUR,           //消息
        FRAGMENT_FIVE,           //我的
    }

    /**
     * @param : [index: 需要创建Fragment的flag, 参数类型是枚举]
     * @return type: android.support.v4.app.Fragment
     * @des: 创建Fragment的方法, 如若已经创建的Fragment不会重新创建
     */
    private Fragment createFragment(FragmentFlag flag) {

        Fragment fragment = mFragmentMap.get(flag);

        if (fragment == null) {
            switch (flag) {
                case FRAGMENT_ONE:
                    fragment = new MenuIndexFragment();
                    break;

                case FRAGMENT_TWO:
                    fragment = new MenuNewsFragment();
                    break;

                case FRAGMENT_THREE:
                    fragment = new MenuVideoFragment();
                    break;
                case FRAGMENT_FOUR:
                    fragment = new MenuMessageFragment();
                    break;
                case FRAGMENT_FIVE:
                    fragment = new MenuMemberFragment();
                    break;
            }
            mFragmentMap.put(flag, fragment);
        }

        return fragment;
    }


    private void replaceFragment(Fragment fragment) {
        if (null != fragment) {
            getSupportFragmentManager().beginTransaction().replace(R.id.fl_content, fragment).commitAllowingStateLoss();
        }
    }

    private long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {

            if ((System.currentTimeMillis() - exitTime) > 2000) {
                showShortToast(getString(R.string.one_more_time_qiut));
                exitTime = System.currentTimeMillis();
            } else {
                //AppManagerUtils.getAppManager().AppExit(mContext);
                finish();
            }
            return true; // 返回true表示执行结束不需继续执行父类按键响应
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        handleIntentWithPushData(intent);
    }

    /*广播接收器*/
    private RefreshMessageReceiver broadcastReceiver;

    /**
     * 广播接收器，接收登陆注销的广播
     */
    class RefreshMessageReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent != null && intent.getAction().equals(BroadcastConstants.ACTION_USER_LOGIN)) {
                mFragmentMap.put(FragmentFlag.FRAGMENT_FOUR, new MenuMessageFragment());
                if (rg_tab.getTag() == FragmentFlag.FRAGMENT_FOUR)
                    replaceFragment(mFragmentMap.get(FragmentFlag.FRAGMENT_FOUR));
            } else if (intent != null && intent.getAction().equals(BroadcastConstants.ACTION_USER_LOGINOUT)) {
                mFragmentMap.put(FragmentFlag.FRAGMENT_FOUR, new MenuMessageFragment());
                if (rg_tab.getTag() == FragmentFlag.FRAGMENT_FOUR)
                    replaceFragment(mFragmentMap.get(FragmentFlag.FRAGMENT_FOUR));
            } else {

            }
        }
    }
}
